package com.yang.dao.impl;

import com.yang.dao.LoginDao;
import com.yang.entity.RoomEntity;
import com.yang.entity.UserEntity;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Transactional
@Repository
public class LoginDaoImpl implements LoginDao {
    public static Logger logger = Logger.getLogger(LoginDaoImpl.class);

    @Autowired
    SessionFactory sessionFactory;

    @Autowired
    HibernateTemplate hibernateTemplate;

    @Override
    public UserEntity selectUserByEmil(String emil) {
        Session session = sessionFactory.openSession();
        Criteria criteria = session.createCriteria(UserEntity.class);
        criteria.add(Restrictions.eq("num",emil));
        UserEntity userEntity = (UserEntity) criteria.uniqueResult();
        session.close();
        return userEntity;
    }

    @Override
    public Boolean updateUser(UserEntity userEntity) {
        try{
            hibernateTemplate.update(userEntity);
        }catch (DataAccessException e){
            e.printStackTrace();
            logger.error("UserEntity更新失败 ： "+e.getMessage());
            return false;
        }
       return true;
    }

    @Override
    public List<RoomEntity> selectRoomEntity() {
        List<RoomEntity> roomList;
        try{
            roomList= (List<RoomEntity>) hibernateTemplate.find("from RoomEntity ");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("房间查询失败");
            return null;
        }
        return roomList;
    }

}
